<template>
  <div>
    <div v-if="showFirstDiv" style="background-color: #f0f8ff;">
      <div style="margin-bottom: 10px;"></div>
      <div style="margin: 0 auto; width: 1100px; text-align: center;">
        <el-form ref="form" :model="formData" label-width="120px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="快递员姓名:" prop="courierName" label-width="100px" label-position="right">
                <el-input v-model="formData.userName" placeholder="请输入快递员姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="快递员电话:" prop="senderName" label-width="100px" label-position="right">
                <el-input v-model="formData.userPhone" placeholder="快递员电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" @click="query">查询</el-button>
                <el-button type="primary" @click="resetValues">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table-container" style="margin-bottom: 10px;"></div>
      <div class="table-container" style="margin-bottom: 50px;">
        <el-table
          :data="expressList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
          style="width: 100%"
          max-height="500"
        >
          <el-table-column prop="" label="序号" width="100"></el-table-column>
          <el-table-column prop="id" label="用户ID" width="150"></el-table-column>
          <el-table-column prop="name" label="姓名" width="150"></el-table-column>
          <el-table-column prop="mobile" label="手机号" width="150"></el-table-column>
          <el-table-column prop="orgName" label="所属机构" width="150"></el-table-column>
          <el-table-column prop="account" label="快递员app账号" width="150"></el-table-column>
          <el-table-column fixed="right" label="操作" width="150" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="DetailsShow(scope.row.org_id,scope.row.id)">作业范围分配</el-button>
              <el-button @click.native.prevent="open(scope.row.id)" type="text" size="small">快递员详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 50px;margin-bottom: 10px">
          <!-- 分页组件 -->
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :page-size="pageSize"
            :current-page="currentPage4"
            :page-sizes="[10, 20, 30, 40]"
            :total="expressList.length"
            layout="total, prev, pager, next, sizes,jumper"
            style="text-align: center; font-size: 6px; margin-top: 15px"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <div v-if="showFirstDiv_to_s">
      <div>

        <el-form class="custom-form" label-position="top" :model="employeeInfo">
          <h1>快递员信息</h1>
          <el-form-item label="员工编号：">{{ employeeInfo.id }}</el-form-item>
          <el-form-item label="快递员姓名：">{{ employeeInfo.name }}</el-form-item>
          <el-form-item label="所属机构：">{{ employeeInfo.orgName }}</el-form-item>
          <el-form-item label="电话：">{{ employeeInfo.password }}</el-form-item>
          <el-button class="custom-btn" @click="goBack">返回</el-button>
        </el-form>
      </div>
    </div>
    <div v-if="showFirstDiv_to">
      <div class="header-container">
        <h2>作业范围分配</h2>
        <div class="buttons" v-if="showButtonDiv">
          <el-button class="custom-btn" @click="showButtonDiv1">编辑</el-button>
          <el-button class="custom-btn" @click="goBack">返回</el-button>
        </div>
        <div class="buttons" v-if="!showButtonDiv">
          <el-button class="custom-btn" @click="save_allocation">保存</el-button>
          <el-button class="custom-btn" @click="showButtonDiv=true;action=false">取消</el-button>
        </div>
      </div>
      <div v-if="!showButtonDiv">
        <div v-if="!action">
          <el-button class="custom-btn" @click="action=true">开始绘制</el-button>
        </div>
        <div v-if="action">
          <el-button class="custom-btn" @click="action=false">完成绘制</el-button>
          <el-button class="custom-btn" @click="eliminateChange()" type="warning">删除绘制</el-button>
          <Button @click="drawerChange(2)">圆形</Button>
        </div>
      </div>
      <div>
        <amap :zoom="zoom" :center="position" ref="grawAmap" style="z-index:99;width:100%;height:600px;">
          <amap-rectangle v-if="drawer_to.mode === 1" :bounds.sync="drawer_to.path" fill-color="#409EFF"
                          stroke-color="#000A58"
          />
          <div v-if="drawer.path">
            <amap-rectangle v-if="drawer.mode === 1" :bounds.sync="drawer.path" :fill-color="'#409EFF'" :stroke-color="'#000A58'" />
          </div>
        </amap>
      </div>
    </div>
  </div>
</template>
<script>

import user from '@/store/modules/user'
import AmapVue from '@/views/logistics/delivery allocation/AmapVue'
import { agencyByOrgId, AllocationRangeList, PostAllocationList, AddallocationRange } from '@/api/base/allocation'

export default {
  components: { AmapVue },
//页面加载之前
  created() {
    PostAllocationList(user.state.orgId).then(res => {
      console.log(res)
      this.expressList = res.data
      this.expressList_to = this.expressList
    })
  },
  data() {
    return {
      Scope_of_couriers :'',//快递员的中心点和半径
      range:{
        id:'',
        user_id:'',
        area_id:'',
        muti_points:'',
      },
      agency: {},//网点范围
      Range: {},//快递员分配范围
      Range_user_id: {},//快递员的用户id
      zoom: 12,//地图级别
      position: [116.378517, 39.865246],//地图中心点
      drawer_to: {
        mode: 1,
        path: []
      },
      drawer: {
        mode: 0,
        path: []
      },
      mouseTool: null,
      objEditor: null,
      pathData: [],
      action: false,
      showButtonDiv: true,
      showFirstDiv_to: '',
      showFirstDiv_to_s: false,
      mapLoaded: false,
      showFirstDiv: true,
      formData: {
        username: '',
        userPhone: ''
      },
      employeeInfo: {},
      pageSize: 10,
      expressList: [],
      expressList_to: [],
      currentPage: 1,
      allocation1: {
        userid: user.state.id,
        pickupTaskNumber: '',
        address: ''
      }
    }
  },
  methods: {
    drawerChange(type) {
      if (this.agency !== null) {
        let vm = this
        vm.drawer.path = null
        vm.drawer.mode = type
        vm.mouseTool ? vm.mouseTool.close(true) : '' //鼠标工具 取消

        let map = vm.$refs.grawAmap.$map //获取地图对象

        //创建鼠标工具
        AMap.plugin(['AMap.MouseTool'], function() {
          let mouseTool = new AMap.MouseTool(map)
          vm.mouseTool = mouseTool
          switch (type) {
            case 1:
              mouseTool.rectangle()//鼠标工具 画矩形
              break
            case 2:
              mouseTool.circle()//鼠标工具 画圆
              break
            case 3:
              mouseTool.polygon()//鼠标工具 画多边形
              break
          }
          // 鼠标工具绘制覆盖物结束触发此事件。
          mouseTool.on('draw', function(e) {
            mouseTool.close(false) //鼠标工具 关闭
            var path = e.obj.getPath()
            let pathArr = [], newDada = []
            path.forEach(e => {
              pathArr.push([e.getLng(), e.getLat()])
            })
            vm.pathData = pathArr
            console.log('圈选：', pathArr)

            //  处理编辑  开始
            switch (type) {
              case 1:
                vm.objEditor = new AMap.RectangleEditor(map, e.obj)//矩形编辑
                break
              case 2:
                vm.objEditor = new AMap.CircleEditor(map, e.obj)//圆形编辑
                break
              case 3:
                vm.objEditor = new AMap.PolyEditor(map, e.obj)//多边形编辑
                break
            }
            console.log(vm.objEditor)
            // 打开编辑功能。调整图形形状
            vm.objEditor.open()

            // 获取圆形的中心点和半径
            if (type === 2) {
              const center = e.obj.getCenter(); // 获取圆形中心点
              const radius = e.obj.getRadius(); // 获取圆形半径
              const integerRadius = Math.floor(radius); // 将小数部分舍去，保留整数部分
              vm.Scope_of_couriers = `[${center.lng},${center.lat}],${integerRadius}`;
              console.log("圆形中心点经纬度：", center);
              console.log("圆形半径：", radius);
            }
            //鼠标调整横向和纵向半径时触发该事件
            vm.objEditor.on('adjust', function(event) {
              pathArr = []
              newDada = event.target.getPath()
              newDada.forEach(el => {
                pathArr.push([el.lng, el.lat])
              })
              vm.pathData = pathArr
              console.log('鼠标调整横向和纵向半径：', pathArr)
              // 获取圆形的中心点和半径
              if (type === 2) {
                const center = e.obj.getCenter(); // 获取圆形中心点
                const radius = e.obj.getRadius(); // 获取圆形半径
                const integerRadius = Math.floor(radius); // 将小数部分舍去，保留整数部分
                vm.Scope_of_couriers = `[${center.lng},${center.lat}],${integerRadius}`;

                console.log("圆形中心点经纬度：", center);
                console.log("圆形半径：", radius);
              }
            })
            //鼠标调整图形位置时触发该事件
            vm.objEditor.on('move', function(event) {
              newDada = []
              pathArr = event.target.getPath()
              pathArr.forEach(el => {
                newDada.push([el.lng, el.lat])
              })
              vm.pathData = newDada
              console.log('鼠标移动圈选区域：', pathArr)
              // 获取圆形的中心点和半径
              if (type === 2) {
                const center = e.obj.getCenter(); // 获取圆形中心点
                const radius = e.obj.getRadius(); // 获取圆形半径
                const integerRadius = Math.floor(radius); // 将小数部分舍去，保留整数部分
                vm.Scope_of_couriers = `[${center.lng},${center.lat}],${integerRadius}`;

                console.log("圆形中心点经纬度：", center);
                console.log("圆形半径：", radius);
              }
            })
            //  处理编辑  结束
          })
        })
      }
    },
    eliminateChange() {
      this.mouseTool ? this.mouseTool.close(true) : '' //鼠标工具 取消
      this.objEditor ? this.objEditor.close() : '' //绘制 取消编辑 关闭编辑功能
      this.drawer.mode = 0
      this.drawer.path = null
    },
    //网点范围
    showButtonDiv1() {
      if (this.agency !== null) {
        console.log(this.agency)
        const muti_points = this.agency.muti_points
        const regex =/\[(-?\d+\.\d+),\s*(-?\d+\.\d+)\],\s*(\d+)/;
        const match = muti_points.match(regex)
        let coordinates = [parseFloat(match[1]), parseFloat(match[2])]
        let value= parseInt(match[3])


        //赋值中心点
        this.position = [coordinates[0], coordinates[1]]
        //网点的范围
        const center = [coordinates[0],coordinates[1]] // 圆心坐标

        const radius = value // 半径，单位：米

        const circles = new AMap.Circle({
          center: center,
          radius: radius,
          strokeColor: '#F00',
          strokeWeight: 1
        })

        circles.setMap(this.$refs.grawAmap.$map)
        const pathCoordinates = circles.getPath().map(point => [point.lng, point.lat])
        this.drawer_to.path = pathCoordinates // 将生成的圆形电子围栏坐标信息存储到 drawer.path 中

        if (this.Range !== null) {
          //快递圆范围
          console.log(this.Range)
          const regexs = /\[(-?\d+\.\d+),\s*(-?\d+\.\d+)\],\s*(\d+)/;
          const mutiple = this.Range.muti_points
          console.log(mutiple)
          const matches =  mutiple.match(regexs);
          let coordinatess = [matches[1], matches[2]]; // 提取经度和纬度，并转换为浮点数
          let values = parseInt(matches[3]); // 提取半径值并转换为整数

          const centers = [coordinatess[0], coordinatess[1]]; // 根据经纬度创建圆心坐标
          const radiuss = values; // 使用提取出的半径值作为半径

          const circless = new AMap.Circle({
            center: centers,
            radius: radiuss,
            strokeColor: '#F00',
            strokeWeight: 2
          })

          circless.setMap(this.$refs.grawAmap.$map)
          const pathCoordinatess = circless.getPath().map(point => [point.lng, point.lat])
          //快递员分配的范围
          this.drawer.mode = 1
          this.drawer.path = pathCoordinatess
        }
      }
      this.showButtonDiv = false
    },

    //作业范围分配
    DetailsShow(org_id, id) {
      console.log(org_id)
      //查询网点范围
      agencyByOrgId(org_id).then(res => {
        this.agency = res.data
      })

      console.log(id)
      this.Range_user_id=id
      //查出快递员范围
      AllocationRangeList(id).then(res => {
        console.log(res)
        this.Range = res.data
      })
      this.showFirstDiv = false
      this.showFirstDiv_to = true
    },
    handleSizeChange(val) {
      this.pageSize = val
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      //console.log(`当前页: ${val}`)
    },

    goBack() {
      // 在这里编写返回操作的逻辑，例如返回上一页或执行其他操作
      this.showFirstDiv = true
      this.showFirstDiv_to_s = false
      this.showFirstDiv_to = false
    },
    open(id) {
      //根据id查询当前员工信息
      this.expressList.forEach(item => {
        if (item.id === id) {
          this.employeeInfo = item
          this.showFirstDiv = false
          this.showFirstDiv_to_s = true
        }
      })

    },
    //清空
    resetValues() {
      this.formData = {
        trackingNumber: '',
        courierName: '',
        address: [],
        statusRemark: '',
        senderName: '',
        status: ''
      }
    },
    //保存分配快递范围
    save_allocation() {
      const drawer_to = this.drawer_to.path
      const drawer = this.pathData

      if (this.areRectanglesMatching(drawer_to, drawer)) {
        console.log(this.Scope_of_couriers)
        this.range.muti_points=this.Scope_of_couriers;
        this.range.user_id=this.Range_user_id
        this.range.area_id=3
        if(this.Range!==null){
          this.range.id=this.Range.id
          this.range.area_id=this.Range.area_id
        }
        AddallocationRange(this.range).then(res => {
          if (parseInt(res.code) === 200) {
            alert('保存成功')
            this.goBack();
            this.eliminateChange();
            this.showButtonDiv=true;
            this.action=false
          }else{
            alert('保存失败')
          }
        })
      } else {
        alert('请选择合适的分配范围')
      }
    },
    //判断是否是是分配范围之内
    areRectanglesMatching(rectangle1, rectangle2) {
      if (rectangle2.length === 0) {
        return false
      }
      let x = []
      let y = []
      let x2 = []
      let y2 = []
      for (let i = 0; i < rectangle1.length; i++) {
        const firstElement = rectangle1[i][0] // 获取当前子数组的第一个元素
        const firstElement1 = rectangle1[i][1] // 获取当前子数组的第一个元素

        x.push(firstElement) // 将第一个元素添加到数组x中
        y.push(firstElement1) // 将第一个元素添加到数组x中
      }
      for (let i = 0; i < rectangle2.length; i++) {
        const firstElement = rectangle2[i][0] // 获取当前子数组的第一个元素
        const firstElement1 = rectangle2[i][1] // 获取当前子数组的第一个元素
        x2.push(firstElement) // 将第一个元素添加到数组x中
        y2.push(firstElement1) // 将第一个元素添加到数组x中
      }
      let xmax = x[0]
      let xmin = x[0]
      let biaoji = true
      for (let i = 1; i < x.length; i++) {
        if (x[i] > xmax) {
          xmax = x[i]
        }
        if (x[i] < xmin) {
          xmin = y[i]
        }
      }
      let ymax = y[0]
      let ymin = y[0]
      for (let i = 1; i < y.length; i++) {
        if (y[i] > ymax) {
          ymax = y[i]
        }
        if (y[i] < ymin) {
          ymin = y[i]
        }
      }
      for (let i = 0; i < x2.length; i++) {
        if (x2[i] > xmax) {
          biaoji = false
        }
        if (x2[i] < xmin) {
          biaoji = false
        }
      }
      for (let i = 0; i < y2.length; i++) {
        if (y2[i] > ymax) {
          biaoji = false
        }
        if (y2[i] < ymin) {
          biaoji = false
        }
      }
      return biaoji
    },
    //条件查询
    query() {
      this.expressList = []
      this.currentPage = 1
      let myBool = false
      // 遍历 formData 对象的属性
      for (const key in this.formData) {
        if (this.formData[key].length > 0) {
          myBool = true
          break
        }
      }
      if (myBool === true) {
        for (const key in this.formData) {
          this.parseNonEmptyData(key, this.formData[key])
        }
      } else {
        // 为空的情况
        this.expressList_to.forEach(item => {
          this.expressList.push(item)
        })
      }

    },
    parseNonEmptyData(fieldName, data) {
      // 执行解析判断的逻辑，此处为示例代码
      if (data !== '') {
        this.expressList_to.forEach(item => {
          if (item[fieldName] === data) {
            this.expressList.push(item)
          }
        })
      }
    }
  }

}
</script>

<style>
.table-container {
  overflow-x: auto;
}

.custom-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.buttons {
  display: flex;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
